import usb
from data.models import Icecream, Scoop, Order , OrderItem, Table
####################################
RQ_SET_LED    = 0
RQ_GET_SWITCH = 1

class BoardControl:
    def __init__(self):
#print "Looking for MCU board..."
        dev = self.find_board()
        if not dev: raise "MCU board not found!"
#print "MCU board found"
        self.handle = dev.open()

    def find_board(self):
    	board = None
    	for bus in usb.busses():
    		for dev in bus.devices:
    			if dev.idVendor == 0x16c0 and dev.idProduct == 0x05dc:
    				return dev
    	return None
    
    def set_led(self,pin,val):
        reqType = usb.TYPE_VENDOR | usb.RECIP_DEVICE | usb.ENDPOINT_OUT
        self.handle.controlMsg(reqType, RQ_SET_LED, None, value=val*256+pin)

    def get_switch(self):
    	reqType = usb.TYPE_VENDOR | usb.RECIP_DEVICE | usb.ENDPOINT_IN
        buf = self.handle.controlMsg(reqType, RQ_GET_SWITCH, 1)
    	return buf[0]

    def start(self):
        while True:
            icecream_id = self.icecream_mode()
            self.set_led(7,1)
            icecream = Icecream.objects.get(pk=icecream_id)
            scoops_list = self.scoops_mode(icecream.scoops_count)
            order_time = Order()
            order_time.save()
            item = OrderItem()
            item.order = order_time
            item.table = Table.objects.get(pk=1)
            item.table.is_free = False
            item.icecream = icecream
            item.save()
            item.scoops = [Scoop.objects.get(pk=i) for i in scoops_list]
            print item
            item.save()

    def icecream_mode(self):
        sw = 0
        while True:
            self.set_led(0,1)
            self.set_led(sw,1)
            tmp_sw = self.get_switch()
            if tmp_sw != 0 and tmp_sw != 7:
                sw = tmp_sw
            if tmp_sw == 7 and sw != 0:
                return sw

    def scoops_mode(self,scoops_num):
        scoops_count = 0
        scoops_list = []
        while True:
            self.set_led(7,1)
            for i in scoops_list:
                self.set_led(i,1) 
            sw = self.get_switch()
            if sw in scoops_list:
                scoops_list.pop(scoops_list.index(sw))
                scoops_count -= 1
            else:
                if sw != 0 and sw != 7 and scoops_count < scoops_num:
                    scoops_list += [sw]
                    scoops_count += 1
                if sw == 7 and scoops_count == scoops_num:
                    return scoops_list


board = BoardControl()


